import type { Env, ShareTextItem } from '../types';

export async function saveShareText(
  env: Env,
  content: string,
  userId: number,
  groupId: number,
  fingerprintId: string
): Promise<{
  success: boolean;
  data?: ShareTextItem;
  error?: string;
}> {
  try {
    const result = await env.DB.prepare(
      'INSERT INTO share_text (content, user_id, group_id, fingerprint_id) VALUES (?, ?, ?, ?) RETURNING *'
    )
      .bind(content, userId, groupId, fingerprintId)
      .first<ShareTextItem>();

    return { success: true, data: result as any };
  } catch (error) {
    console.error('Error saving share text:', error);
    return { success: false, error: 'Failed to save text' };
  }
}

export async function getShareTextList(
  env: Env
): Promise<{
  success: boolean;
  data?: ShareTextItem[];
  error?: string;
}> {
  try {
    const result = await env.DB.prepare('SELECT * FROM share_text ORDER BY create_at DESC')
      .all<ShareTextItem>();

    return { success: true, data: result.results };
  } catch (error) {
    console.error('Error getting share text list:', error);
    return { success: false, error: 'Failed to get text list' };
  }
}